package com.appkubes.fintech.restful.application.system.service.impl;

import com.appkubes.common.utils.data.date.DateUtils;
import com.appkubes.fintech.core.constant.order.RentOrderPeriodCode;
import com.appkubes.fintech.core.po.FintechSettings;
import com.appkubes.fintech.restful.application.system.dao.SettingsDao;
import com.appkubes.fintech.restful.application.system.entity.constant.SettingKeyCode;
import com.appkubes.fintech.restful.application.system.entity.dto.RentPeriodSettingDTO;
import com.appkubes.fintech.restful.application.system.entity.vo.RentPeriodSettingVO;
import com.appkubes.fintech.restful.application.system.service.SettingService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: Rongjie
 * @Date: 2020/1/5 20:18
 * @Description:
 */
@Service
public class SettingServiceImpl implements SettingService {

    @Resource
    SettingsDao settingsDao;


    @Override
    public RentPeriodSettingDTO getPeriodSetting(RentPeriodSettingVO rentPeriodSettingVO) {
        FintechSettings rentEffectType = getSetting(SettingKeyCode.RentFffectType);
        FintechSettings gracePeriod = getSetting(SettingKeyCode.GracePeriod);
        Integer graceHour = Integer.valueOf(gracePeriod.getSettingValue());

        RentPeriodSettingDTO periodSettingDTO = new RentPeriodSettingDTO();
        periodSettingDTO.setRentEffectType(rentEffectType.getSettingValue());
        periodSettingDTO.setGracePeriod(graceHour);

        Date startTime = new Date(), endTime;

        //计算起租时间
        if ("MORROW".equalsIgnoreCase(rentEffectType.getSettingValue())) {
            startTime = DateUtils.getDayBeginTime(startTime);
            startTime = DateUtils.addDate(startTime, 0, 0, 1, 0, 0, 0, 0);
        }

        //获取租期天数, 计算结束时间
        RentOrderPeriodCode rentOrderPeriodCode = RentOrderPeriodCode.valueOf(rentPeriodSettingVO.getPeriodCode());

        //结束时间=起始时间+租期+宽限期
        endTime = DateUtils.addDate(startTime, 0, 0, rentOrderPeriodCode.getPeriodDays(), graceHour, 0, 0, 0);

        periodSettingDTO.setRentStartDate(startTime);
        periodSettingDTO.setRentEndDate(endTime);

        return periodSettingDTO;
    }

    FintechSettings getSetting(SettingKeyCode keyCode) {
        FintechSettings settings = settingsDao.selectByPrimaryKey(keyCode.name());
        if (settings == null) {
            settings = new FintechSettings();
            settings.setSettingKey(keyCode.name());
            settings.setSettingValue(keyCode.getDefaultValue());
            settings.setDescription(keyCode.getDescription());
            settings.setCreateTime(new Date());

            settingsDao.insertSelective(settings);
        }
        return settings;
    }


}
